package com.sbxBase.service.impl;

import com.sbxBase.mapper.RouteMapper;
import com.sbxBase.service.RouteService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.entity.sbxBase.Route;
import com.common.utils.RequestUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RouteServiceImpl implements RouteService {

    @Resource
    private RouteMapper routeMapper;

    @Override
    public List<Route> getRouterByRoleId() {
        String roleId = RequestUtil.getRoleId();
        //根据roleId parentId  查询到一级路由
        List<Route> routes = routeMapper.selectList(new LambdaQueryWrapper<Route>()
                .eq(Route::getRoleId, roleId)
                .eq(Route::getParentId, "root"));
        getChildren(routes);
        return routes;
    }

    @Override
    public List<Route> getAllRouter() {
        String roleId = RequestUtil.getRoleId();
        if (StringUtils.isEmpty(roleId) || !"0".equalsIgnoreCase(roleId)) {
            throw new IllegalArgumentException("没有权限");
        }
        List<Route> routes = routeMapper.selectList(new LambdaQueryWrapper<Route>()
                .eq(Route::getParentId, "root"));
        getChildren(routes);
        return routes;
    }

    private void getChildren(List<Route> routes) {

        if (CollectionUtils.isEmpty(routes)) {
            return;
        }
        for (Route route : routes) {

            List<Route> childrenList = routeMapper.selectList(new LambdaQueryWrapper<Route>().eq(Route::getParentId, route.getId()));
            if (!CollectionUtils.isEmpty(childrenList)) {
                route.setChildren(childrenList);
                getChildren(childrenList);
            }
        }
    }
}
